<template>
  <div class="city-alphabet">
    <ul class="alphabet-list"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
    >
      <li v-for="(item, index) of alphas" :key="index"
          @click="handleAlphaClick(index, $event)"
          :class="[selfAlphaIndex === index ? alphaActiveClass : '']"
          :ref="item"
      >{{ item }}</li>
    </ul>
  </div>
</template>

<script>
  export default {
    name: "CityAlphabet",
    data() {
      return {
        alphaActiveClass: 'alpha-active',
        selfAlphaIndex: this.currentAlphaIndex,
        timer: null,
        startY: 0,
        isTouchStart: false
      }
    },
    updated() {
      // 第一个字母
      this.startY = this.$refs["A"][0].offsetTop;
    },
    methods: {
      handleAlphaClick(index, event) {
        let str = event.target.innerText;
        // console.log(str);
        this.selfAlphaIndex = index;
        // console.log(index);
        this.$emit("alpha-click", str);
      },

      handleTouchStart(event) {
        this.isTouchStart = true;
      },
      handleTouchMove(event) {

        if (!this.isTouchStart) {
          return;
        }

        if (!!this.timer) {
          console.log("清理timer");
          clearTimeout(this.timer);
        }

        this.timer = setTimeout(() => {
          let clientY = event.changedTouches[0].clientY;
          // 获取对应的字母
          let index = Math.floor((clientY - this.startY - 79) / 20);
          // console.log(clientY + ":" + startY)
          if (index >= 0 && index < this.alphas.length) {
            this.selfAlphaIndex = index;
            let alpha = this.alphas[index];
            this.$emit("scroll-change", alpha);
            console.log(alpha);
          }
        });

      },
      handleTouchEnd(event) {
        this.isTouchStart = false;
      }
    },
    props: {
      alphas: Array,
      currentAlphaIndex: Number,
    }
  }
</script>

<style scoped lang="scss">

  @import "~styles/variables.scss";

  .city-alphabet {
    position: absolute;
    z-index: 10;
    top: 1.58rem;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    .alphabet-list {
      width: .6rem;
      justify-content: center;
      margin: auto 0;
      text-align: center;

      li {
        line-height: .4rem;
        color: $bgColor;
      }

      .alpha-active {
        color: #CCC
      }

    }
  }

</style>